package com.situ.mall.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.situ.mall.common.entity.OrderInfo;
import com.situ.mall.common.mapper.OrderInfoMapper;
import com.situ.mall.common.service.IPayService;
import com.situ.mall.common.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayServiceImpl implements IPayService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public String pay(Integer id) throws AlipayApiException {
        OrderInfo oi = orderInfoMapper.selectById(id);

        //创建一个支付宝的请求的client 连上支付宝
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getServerUrl(), alipayConfig.getAppId(), alipayConfig.getPrivateKey(), "json", "UTF-8", alipayConfig.getPublicKey(), alipayConfig.getSignType());

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //预订单创建完成后  接受支付宝请求的地址
        request.setNotifyUrl("http://443a77f9.r6.cpolar.top/order/notify");
        //业务
        JSONObject bizContent = new JSONObject();
        //订单号
        bizContent.put("out_trade_no", oi.getCode());
        //订单金额
        bizContent.put("total_amount", oi.getPrice());
        //订单描述
        bizContent.put("subject", "华为商城订单");
        request.setBizContent(bizContent.toString());//发请求
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            //获取二维码
            return response.getQrCode();

        } else {
            System.out.println("调用失败");
        }
        return null;
    }
}
